package com.suncaper.wcss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suncaper.wcss.common.BaseConstant;
import com.suncaper.wcss.common.PageDTO;
import com.suncaper.wcss.common.utls.SessionUtils;
import com.suncaper.wcss.model.domain.*;
import com.suncaper.wcss.mapper.ApplicationMapper;
import com.suncaper.wcss.model.dto.AuditHistoryDTO;
import com.suncaper.wcss.model.vo.ApplicationVO;
import com.suncaper.wcss.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.suncaper.wcss.common.BaseConstant.*;

/**
 * <p>
 * 申请表 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-11-16
 */
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements ApplicationService {

    @Autowired
    private StudentDataService studentDataService;
    @Autowired
    private BatchSettingService batchSettingService;
    @Autowired
    private OrganizationLevelService organizationLevelService;
    @Autowired
    private UserManageService userManageService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private RoleFlowSettingService roleFlowSettingService;
    @Autowired
    private AuditHistoryService auditHistoryService;

    @Override
    public Boolean create(Application application) {
        //获取当前用户
        User user = SessionUtils.getCurrentUserInfo();
        //获取当前批次
        BatchSetting batchSetting = batchSettingService.curBatch();
        //判断这个用户当前批次是否已有申请
        QueryWrapper<Application> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Application::getSn,user.getSn()).eq(Application::getBatchId,batchSetting.getId());
        Application one = baseMapper.selectOne(queryWrapper);
        if(Objects.nonNull(one)){
            return false;
        }

        application.setApplyDate(LocalDate.now());
        application.setSn(user.getSn());
        application.setName(user.getName());
        //获取学生信息
        QueryWrapper<StudentData> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StudentData::getSn, user.getSn());
        StudentData student = studentDataService.getOne(wrapper);
        application.setGender(BaseConstant.SEX_VALUE_M.equals(student.getGender()) ? SEX_KEY_M : SEX_KEY_F);
        application.setCollegeSn(student.getCollegeCode());
        application.setCollegeName(student.getCollege());
        application.setMajorName(student.getMajor());
        application.setMajorSn(student.getMajorCode());
        application.setClassName(student.getClazz());
        application.setClassSn(student.getClassCode());

        application.setDifficultyLevel(batchSetting.getDifficultyLevel());
        application.setCurrentNodeCode(NODE_TEACHER);
        application.setStatus(STATUS_DSH);
        baseMapper.insert(application);
        return true;
    }


    @Override
    public Page<ApplicationVO> waitAudit(PageDTO pageDTO, Application application) {
        User user = SessionUtils.getCurrentUserInfo();
        //  Page<Application> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        Page<ApplicationVO> voPage = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        //QueryWrapper<Application> queryWrapper = new QueryWrapper<>();
        QueryWrapper<UserManage> wrapper = new QueryWrapper<>();
        application.setStatus(STATUS_DSH);
        if (ROLE_TEACHER.equals(user.getRoleId())) {
            //辅导员
            //获取辅导员所带组织
            wrapper.lambda().eq(UserManage::getUserSn, user.getSn()).eq(UserManage::getRoleId, ROLE_TEACHER);
            List<UserManage> list = userManageService.list(wrapper);
            //所带班级sn
            List<String> clazzSn = list.stream().map(x -> x.getOrganizationSN()).collect(Collectors.toList());
            //构建申请的查询条件
            //辅导员待我审核(自己所带班级、当前节点为1、审核状态为DSH)
//            queryWrapper.lambda().in(Application::getClassSn, clazzSn)
//                    .eq(Application::getCurrentNodeCode, NODE_TEACHER)
//                    .eq(Application::getStatus, STATUS_DSH);
            application.setCurrentNodeCode(NODE_TEACHER);
            voPage = baseMapper.teacherAppList(voPage, application, clazzSn);
        } else if (ROLE_COLLEGE.equals(user.getRoleId())) {
            //学院
            wrapper.lambda().eq(UserManage::getUserSn, user.getSn()).eq(UserManage::getRoleId, ROLE_COLLEGE);
            List<UserManage> list = userManageService.list(wrapper);
            //所带学院sn
            List<String> collegeSn = list.stream().map(x -> x.getOrganizationSN()).collect(Collectors.toList());
//            queryWrapper.lambda().in(Application::getCollegeSn, collegeSn)
//                    .eq(Application::getCurrentNodeCode, NODE_COLLEGE)
//                    .eq(Application::getStatus, STATUS_DSH);
            application.setCurrentNodeCode(NODE_COLLEGE);

            voPage = baseMapper.conllegeAppList(voPage, application, collegeSn);
        } else if (ROLE_SCHOOL.equals(user.getRoleId())) {
            //学校
//            queryWrapper.lambda().eq(Application::getCurrentNodeCode, NODE_SCHOOL)
//                    .eq(Application::getStatus, STATUS_DSH);
            application.setCurrentNodeCode(NODE_SCHOOL);
            voPage = baseMapper.schoolAppList(voPage, application);
        }
        // page = baseMapper.selectPage(page, queryWrapper);
        //diboot

//        voPage.setTotal(page.getTotal());
//        voPage.setPages(page.getPages());
//        List<ApplicationVO> voList = page.getRecords().stream().map(x -> {
//            ApplicationVO vo = new ApplicationVO(x);
//            vo.setDifficultyValue(dictionaryService.getValueByKey(x.getDifficultyLevel(),DIFFICULTY));
//            vo.setNodeName(roleFlowSettingService.getCurNodeByCode(x.getCurrentNodeCode()).getNodeName());
//            vo.setStatusValue(dictionaryService.getValueByKey(x.getStatus(),STATUS));
//            return vo;
//        }).collect(Collectors.toList());
//        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    @Transactional
    public void audit(AuditHistory history) {
        User user = SessionUtils.getCurrentUserInfo();
        history.setAuditBy(user.getSn());
        history.setAuditorName(user.getName());
        history.setAuditNodeName(roleFlowSettingService.getCurNodeByCode(history.getAuditNodeCode()).getNodeName());
        auditHistoryService.save(history);
        //获取原申请
        Application application = baseMapper.selectById(history.getApplicationId());
        //判断审核状态，如果是成功，进入下一个节点，失败，直接修改申请状态
        if (STATUS_BTG.equals(history.getStatus())) {
            //失败
            application.setStatus(STATUS_BTG);
            application.setAuditComment(history.getAuditComment());
        } else {
            //成功
            //先获取当前节点的下一个节点
            RoleFlowSetting nextNode = roleFlowSettingService.getNextNodeByCode(history.getAuditNodeCode());
            //考虑是不是学校这一步，如果是学校，整个流程结束，状态为TG
            if (NODE_END.equals(nextNode.getNodeCode())) {
                application.setStatus(STATUS_TG);
                application.setAuditComment(history.getAuditComment());
            }
            //如果不是学校，表示流程还要继续
            application.setCurrentNodeCode(nextNode.getNodeCode());
        }
        baseMapper.updateById(application);
    }

    @Override
    public void audits(AuditHistoryDTO history) {
        history.getApplicationIds().stream().map(x -> new AuditHistory().setApplicationId(x)
                .setAuditNodeCode(history.getAuditNodeCode())
                .setStatus(history.getStatus())
                .setAuditComment(history.getAuditComment())).forEach(x -> audit(x));
    }

    @Override
    public Page<ApplicationVO> pageList(PageDTO pageDTO, Application application) {
        User user = SessionUtils.getCurrentUserInfo();
        Page<ApplicationVO> voPage = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        QueryWrapper<UserManage> wrapper = new QueryWrapper<>();
        if (ROLE_TEACHER.equals(user.getRoleId())) {
            //辅导员
            wrapper.lambda().eq(UserManage::getUserSn, user.getSn()).eq(UserManage::getRoleId, ROLE_TEACHER);
            List<UserManage> list = userManageService.list(wrapper);
            //所带班级sn
            List<String> clazzSn = list.stream().map(x -> x.getOrganizationSN()).collect(Collectors.toList());
            voPage = baseMapper.teacherAppList(voPage, application, clazzSn);
        } else if (ROLE_COLLEGE.equals(user.getRoleId())) {
            //学院
            wrapper.lambda().eq(UserManage::getUserSn, user.getSn()).eq(UserManage::getRoleId, ROLE_COLLEGE);
            List<UserManage> list = userManageService.list(wrapper);
            //所带学院sn
            List<String> collegeSn = list.stream().map(x -> x.getOrganizationSN()).collect(Collectors.toList());
            voPage = baseMapper.conllegeAppList(voPage, application, collegeSn);
        } else if (ROLE_SCHOOL.equals(user.getRoleId())) {
            //学校
            voPage = baseMapper.schoolAppList(voPage, application);
        } else if(ROLE_STUDENT.equals(user.getRoleId())){
            application.setSn(user.getSn());
            voPage = baseMapper.stuAppList(voPage,application);
        }
        return voPage;
    }

    @Override
    public ApplicationVO getBySnAndBatchId() {
        //获取当前用户
        User user = SessionUtils.getCurrentUserInfo();
        //获取当前批次
        BatchSetting batchSetting = batchSettingService.curBatch();
        //判断这个用户当前批次是否已有申请
        ApplicationVO vo = baseMapper.getBySnAndBatchId(user.getSn(),batchSetting.getId());
        return vo;
    }

    @Override
    public void checkPro(Application application) {
        //id proid skuid
        baseMapper.updateById(application);
    }
}
